package jp.tuyano.sample.server;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import jp.tuyano.core.PMF;
import jp.tuyano.sample.client.form.EmployeeForm;
import jp.tuyano.sample.client.registration.RegisterService;
import jp.tuyano.sample.server.entity.Employee;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;


public class RegisterServiceImpl extends RemoteServiceServlet implements
        RegisterService {

    private static final long serialVersionUID = 1L;
    
    private PersistenceManager pm;
    
    public String registerEmployee(EmployeeForm form) {
        
        String id = form.getId();
        String lastName = form.getLastName();
        String firstName = form.getFirstName();
        String sex = form.getSex();
        Date birthDate = form.getEnterDate();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Employee emp = new Employee(id, lastName, firstName, sex,
                df.format(birthDate));
        
        boolean isSuccess = validateDuplication(id);
        
        if (!isSuccess) {
            return "登録できません : IDが重複しています。";
        }
        
        pm = PMF.get().getPersistenceManager();
        
        try {
            pm.makePersistent(emp);
        } catch (RuntimeException e) {
            e.printStackTrace();
            
        } finally {
            pm.close();
        }
        return "登録が完了しました。";
    }

    public boolean isAvailable(String id) {
        
        return validateDuplication(id);
    }
    
    private boolean validateDuplication(String id) {
        pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Employee.class);
        query.setFilter("id == :id");
        @SuppressWarnings("unchecked")
        List<Employee> result = (List<Employee>) query.execute(id);
        if (result.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}
